import { Injectable } from '@nestjs/common';
import { Response } from 'src/utils/response';
import { getCurrentTime, beanCopyArray, formatTime } from 'src/utils';
import { ArticleVO } from './article.vo';
import { ArticleRepository } from './article.repostiory';

@Injectable()
export class ArticleService {
  constructor(private readonly articleRepository: ArticleRepository) {}

  // 获取文章列表
  async queryArticleList() {
    const articles = await this.articleRepository.queryRepository();
    const VO = new ArticleVO();
    const result: ArticleVO[] = beanCopyArray<ArticleVO>(VO, articles);
    result.forEach((item) => {
      formatTime(item, ['createdAt', 'updatedAt', 'publishedAt'], 'YYYY-MM-DD');
    });
    return Response.success({ data: result });
  }

  // 获取已发布的文章列表
  async queryPublishedArticleList() {
    const articles = await this.articleRepository.queryPublishedRepository();
    const VO = new ArticleVO();
    const result: ArticleVO[] = beanCopyArray<ArticleVO>(VO, articles);
    result.forEach((item) => {
      formatTime(item, ['createdAt', 'updatedAt', 'publishedAt'], 'YYYY-MM-DD');
    });
    return Response.success({ data: result });
  }

  // 文章阅读量
  async updateArticleViews(id: number) {
    const article = await this.articleRepository.queryOneRepository(id);
    if (!article) {
      return Response.error({ message: '文章不存在' });
    }
    article.views = `${Number(article.views) + 1}`;
    await this.articleRepository.updateRepository(id, article);
    return Response.success({ message: '更新成功' });
  }

  // 发布文章
  async publishedArticleService(id: number) {
    if (!id) {
      return Response.error({ message: 'id不能为空' });
    }
    await this.articleRepository.publishedArticleRepository(id, {
      status: 'published',
      publishedAt: getCurrentTime('YYYY-MM-DD HH:mm:ss'),
    });
    return Response.success({ message: '发布成功' });
  }

  // 获取阅读量前6的文章
  async getTop6Article() {
    const articles = await this.articleRepository.queryTop6ArticleRepository();
    return Response.success({ data: articles });
  }

  // 添加文章
  async insertArticle(article: any) {
    try {
      article = {
        ...article,
        delFlag: 0,
        status: 'draft',
        views: '0',
        likes: '0',
        commentsCount: '0',
      };
      await this.articleRepository.addRepository(article);
      return Response.success({ message: '添加成功' });
    } catch (error) {
      return Response.error({ message: error });
    }
  }

  // 更新文章
  async updateArticle(id: number, article: any) {
    if (!id) {
      return Response.error({ message: 'id不能为空' });
    }
    try {
      await this.articleRepository.updateRepository(id, {
        ...article,
      });
      return Response.success({ message: '更新成功' });
    } catch (error) {
      return Response.error({ message: error });
    }
  }

  // 删除文章
  async removeArticle(id: number) {
    const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
    try {
      await this.articleRepository.deleteRepository(id, currentTime);
      return Response.success({ message: '删除成功' });
    } catch (error) {
      return Response.error({ message: error });
    }
  }

  // 获取文章详情
  async getArticleDetail(id: number) {
    if (!id) {
      return Response.error({ message: 'id不能为空' });
    }
    const article = await this.articleRepository.queryOneRepository(id);
    if (!article) {
      return Response.error({ message: '文章不存在' });
    }
    const VO = new ArticleVO();
    const result = Object.assign(VO, article);
    formatTime(result, ['createdAt', 'updatedAt', 'publishedAt'], 'YYYY-MM-DD');
    return Response.success({ data: result });
  }

  // 点赞文章
  async likeArticle(id: number) {
    if (!id) {
      return Response.error({ message: 'id不能为空' });
    }
    const article = await this.articleRepository.queryOneRepository(id);
    if (!article) {
      return Response.error({ message: '文章不存在' });
    }
    article.likes = `${Number(article.likes || 0) + 1}`;
    await this.articleRepository.updateRepository(id, article);
    return Response.success({ message: '点赞成功' });
  }

  // 获取热门文章（按阅读量和点赞量排序，取前5）
  async getHotArticles() {
    const articles = await this.articleRepository.queryRepository();
    const sorted = articles
      .sort((a, b) => {
        const viewsA = Number(a.views || 0);
        const viewsB = Number(b.views || 0);
        const likesA = Number(a.likes || 0);
        const likesB = Number(b.likes || 0);
        // 可自定义权重，这里简单相加
        return viewsB + likesB - (viewsA + likesA);
      })
      .slice(0, 5);
    return Response.success({ data: sorted });
  }

  // 获取最新文章（按发布时间排序，取前9）
  async getLatestArticles() {
    const articles = await this.articleRepository.queryPublishedRepository();
    const sorted = articles
      .sort((a, b) => {
        const timeA = new Date(a.publishedAt || a.createdAt).getTime();
        const timeB = new Date(b.publishedAt || b.createdAt).getTime();
        return timeB - timeA;
      })
      .slice(0, 9);
    return Response.success({ data: sorted });
  }
}
